package com.init.service.login.service.impl;
/**
 *
 **/

import com.init.common.constant.Constants;
import com.init.common.core.domain.AjaxResult;
import com.init.common.core.redis.RedisCache;
import com.init.common.utils.TokenUtils;
import com.init.service.login.req.UserLoginReq;
import com.init.service.login.resp.UserTokenResp;
import com.init.service.login.service.IUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author weiwei
 * @Date 2021-10-12 15:59
 * @description 登录实现
 **/
@Service
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private RedisCache redisCache;

    @Override
    public AjaxResult login(UserLoginReq req) {

        //todo 查询数据库密码校验
        String account = req.getAccount();


        //todo 构建token
        return AjaxResult.success(generateToken(1L,"ww"));
    }

    @Override
    public void loginOut(Long userId) {
        redisCache.deleteObject(Constants.USER_TOKEN_REDIS_KEY);
    }

    @Override
    public AjaxResult refreshToken(Long userId) {
        //todo 查询名称


        return AjaxResult.success(generateToken(userId,"wwR"));
    }

    private UserTokenResp generateToken(Long id,String name){
        UserTokenResp tokenResp = new UserTokenResp();
        tokenResp.setUserId(id);
        tokenResp.setUserName(name);
        tokenResp.setToken(TokenUtils.generateToken(Constants.USER_TOKEN_KEY, id + ""));
        tokenResp.setRefreshToken(TokenUtils.generateRefreshToken(Constants.USER_TOKEN_KEY, id + "" + ""));
        redisCache.setCacheObject(Constants.USER_TOKEN_REDIS_KEY,id,Constants.EXPIRE_TIME, TimeUnit.MILLISECONDS);
        return tokenResp;
    }
}
